package com.wenyl.juc.thread.readWriteLockTest;

import lombok.Data;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Swimming Dragon
 * @description: TODO
 * @date 2024年11月07日 12:04
 */
@Data
public class User {
    private String username;
    private MyCount myCount;
    ReadWriteLock readWriteLock;
    User(String username,MyCount myCount){
        this.username = username;
        this.myCount = myCount;
        this.readWriteLock = new ReentrantReadWriteLock();
    }
    public void getCash(){
        new Thread(){
            @Override
            public void run(){
                readWriteLock.readLock().lock();
                try {
                    System.out.println(Thread.currentThread().getName()+ " getCash start");
                    myCount.getCash();
                    Thread.sleep(200);
                    System.out.println(Thread.currentThread().getName()+ " getCash end");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    readWriteLock.readLock().unlock();
                }

            }
        }.start();
    }
    public void setCash(int addCash){
        new Thread(){
            @Override
            public void run(){
                readWriteLock.writeLock().lock();

                try {
                    System.out.println(Thread.currentThread().getName()+ " setCash start");
                    myCount.setCash(addCash);
                    Thread.sleep(500);
                    System.out.println(Thread.currentThread().getName()+ " setCash end");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    readWriteLock.writeLock().unlock();
                }


            }
        }.start();
    }
}
